package czStvDpds.network;

import czStvDpds.centrallogic.Logic;
import czStvDpds.centrallogic.PlayerMovement;
import czStvDpds.logging.Logging;
import czStvDpds.movement.Player;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Strouhal,JT
 */
public class ThreadReceiver extends Thread {

    protected DatagramSocket datagramSocket;
    public static int RECEIVING_PORT = 7876;//původní 9876
    public static int MAX_SIZE_RECEIVED_DATA = 512;
    private Logic logic = null;
    private boolean bezim = true;
    
    private PotvrzeniThread threadOdkaz;

    public ThreadReceiver(Logic l, PotvrzeniThread tO) {
        Logging.getMainLogger().log(Level.ALL, "bude proveden kod v konstruktoru TreadReceiver");

        try {
            datagramSocket = new DatagramSocket(RECEIVING_PORT);
            Logging.getMainLogger().log(Level.SEVERE, "přímo z try catch");          
            
        } catch (SocketException ex) {
            Logging.getMainLogger().log(Level.SEVERE, ex.getMessage());
            Logger.getLogger(ThreadReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
        Logging.getMainLogger().log(Level.ALL, "datagramsocket inicializovan");

        logic = l;
        threadOdkaz=tO;
        
    }

       
    
    public void run() {
        DatagramPacket datagramPacket;
        
        while (bezim == true) {
            datagramPacket = new DatagramPacket(new byte[MAX_SIZE_RECEIVED_DATA], MAX_SIZE_RECEIVED_DATA);
            try {
                datagramSocket.receive(datagramPacket);
                System.out.println("paket přijat");
                zpracujPaket(datagramPacket);
            } catch (IOException ex) {
                Logging.getMainLogger().log(Level.SEVERE, ex.getLocalizedMessage());
            }
        }

    }

    private void zpracujPaket(DatagramPacket datagramPacket) {
        byte bajt[] = new byte[datagramPacket.getLength()];
        bajt = datagramPacket.getData();
        String zprava = new String(bajt);
        
        Scanner scanner = new Scanner(zprava);
        scanner.useDelimiter("-");
               
       
        if (scanner.hasNextInt()) {
            int i = scanner.nextInt();
             Logging.getMainLogger().log(Level.SEVERE, "NETWORK:",i);
            if (i == 00) {
                Logging.getMainLogger().log(Level.SEVERE, "NETWORK: zpracovávám 00");
                zpracujZero(scanner);
            } else if (i == 01) {
                Logging.getMainLogger().log(Level.SEVERE, "NETWORK: zpracovávám 01");
                zpracujZeroOne(scanner);                
            } else if (i == 11) {
                Logging.getMainLogger().log(Level.SEVERE, "NETWORK: zpracovávám 11");
                zpracujFirst(scanner);
            } else if (i == 22) {
                Logging.getMainLogger().log(Level.SEVERE, "NETWORK: zpracovávám 22");
                zpracujSecond(scanner);
            } else if (i == 33) {
                Logging.getMainLogger().log(Level.SEVERE, "NETWORK: zpracovávám 33");
                zpracujThird(scanner);
            } else if (i == 44) {
                Logging.getMainLogger().log(Level.SEVERE, "NETWORK: zpracovávám 44");
                zpracujFourth(scanner);
            } else if (i == 55) {
                Logger.getGlobal().log(Level.ALL, "NETWORK: zpracovávám 55");
                zpracujFifth(scanner);
            }
        } else {
            
            if (scanner.nextLine().substring(0, 5).compareTo("konec") == 0) {
                if (datagramPacket.getAddress().equals(InetAddress.getLoopbackAddress())) {
                    Logging.getMainLogger().log(Level.SEVERE, "ukonceni vlakna ThreadReceiver");
                    datagramSocket.disconnect();
                    datagramSocket.close();
                }
            }
        }
    }

    protected void zpracujZero(Scanner scanner) {
        //ex.: 00--nick-id 
        String a = new String(scanner.next());
        int i = scanner.nextInt();
        logic.addPlayer(new Player(10, 10, 0, a), i);
    }

    protected void zpracujZeroOne(Scanner scanner) {       
             
        Logging.getMainLogger().log(Level.SEVERE, "Pripojeni potvrzeno");
        threadOdkaz.ukonciVlakno();
        //putDataPack(p);
    }

    protected void zpracujFirst(Scanner scanner) {
        //11-souradnice_X-souradnice_y-uhel_smeru-objekt(id)

        double x = scanner.nextDouble();
        double y = scanner.nextDouble();
        double a = scanner.nextDouble();
        int id = scanner.nextInt();
        logic.movePlayer(new PlayerMovement(id, x, y, a));

    }

    protected void zpracujSecond(Scanner scanner) {

        throw new UnsupportedOperationException("Not supported yet.");
    }

    protected void zpracujThird(Scanner scanner) {
        //ex.: 33-hrac_id-pocet_zivotu 
        throw new UnsupportedOperationException("Not supported yet.");
    }

    protected void zpracujFourth(Scanner scanner) {
        //ex.: 44-zmena_na_x-zmena_na_y-zmeneno_na 
        throw new UnsupportedOperationException("Not supported yet.");
    }

    protected void zpracujFifth(Scanner scanner) {
        //55-hrac_id                  
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void ukonciVlakno() {
        bezim = false;        
        Logger.getGlobal().log(Level.ALL, "ukonceni vlakna ThreadReceiver");
        try {
            DatagramSocket ds = new DatagramSocket(4598);
            ds.send(new DatagramPacket("konec".getBytes(), 5, InetAddress.getLoopbackAddress(), 7876));
            ds.close();
        } catch (SocketException ex) {
            Logger.getLogger(ThreadReceiver.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ThreadReceiver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}